package java10;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

//事务操作
public class JdbcTest08 {
    public static void main(String[] args){
        Connection conn = null;
        PreparedStatement pstmt1 = null;
        PreparedStatement pstmt2 = null;
        try {
            //1.获取连接
            conn = JDBCUtils.getConnection();
            //开启事务
            conn.setAutoCommit(false);
            System.out.println("开启事务！");
            //2.定义sql,张三 - 500
            String sql1 = "update account set balance = balance - ? where id = ?";
            //李四 + 500
            String sql2 = "update account set balance = balance + ? where id = ?";
            //3.获取sql执行对象
            pstmt1 = conn.prepareStatement(sql1);
            pstmt2 = conn.prepareStatement(sql2);
            //4.设置参数,设置第一个sql语句的第一个问号的参数
            pstmt1.setDouble(1,500);
            //设置第一个sql语句的第二个问号的参数
            pstmt1.setInt(2,1);
            //设置第二个sql语句的第一个问号的参数
            pstmt2.setDouble(1,500);
            //设置第二个sql语句的第二个问号的参数
            pstmt2.setInt(2,2);
            //5.执行sql
            pstmt1.executeUpdate();
            int i = 3 / 0;
            pstmt2.executeUpdate();
            //提交事务
            conn.commit();
            System.out.println("提交事务！");
        } catch (Exception e) {
            //事务回滚
            try {
                if(conn != null){
                    conn.rollback();
                    System.out.println("回滚事务！");
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            JDBCUtils.close(pstmt1,conn);
            JDBCUtils.close(pstmt2,null);
        }
    }
}
